package hn.cch.common.quartz;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;

@Scope(value = "singleton")
@Component
public class QuartzJobManager {


    private static final Logger logger = LoggerFactory.getLogger(QuartzJobManager.class);

    @Autowired
    private Scheduler scheduler;


    /**
     * 初始化所有定时任务
     */
    public void initJobs() {

        HashMap<Class<? extends Job>, String> jobMap = new HashMap<>();//存储定时任务数据
        // jobMap.put(QuartzJob.class, "0 * * * * ?");//可以添加多个定时任务


        for (Class<? extends Job> jobClass:jobMap.keySet()) {
            if (!addJob(jobClass, jobMap.get(jobClass))){
                System.exit(-1);//异常退出
            }
        }
    }


    /**
     * 添加单个定时任务
     * @param jobClass
     * @param cronText
     * @return
     */
    public boolean addJob(Class<? extends Job> jobClass, String cronText) {

            try {
                CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                        .withSchedule(CronScheduleBuilder.cronSchedule(cronText))
                        .withIdentity(jobClass.getName(), jobClass.getName()).build();

                JobDetail jobDetail = JobBuilder.newJob(jobClass).storeDurably()
                        .withIdentity(jobClass.getName(), jobClass.getName()).build();

            Date date = scheduler.scheduleJob(jobDetail, cronTrigger);
            logger.info("add job first:{}", date);
            return true;
        } catch (SchedulerException e) {
            logger.error("add job error:{}", e);
            return false;
        }
    }


}
